package osirix.ce;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class Util {

	private static String convertToHex(byte[] data) {
		StringBuilder buf = new StringBuilder();
		for (int i = 0; i < data.length; i++) {
			int halfbyte = (data[i] >>> 4) & 0x0F;
			int two_halfs = 0;
			do {
				if ((0 <= halfbyte) && (halfbyte <= 9))
					buf.append((char) ('0' + halfbyte));
				else
					buf.append((char) ('a' + (halfbyte - 10)));
				halfbyte = data[i] & 0x0F;
			} while (two_halfs++ < 1);
		}
		return buf.toString();

	}

	public static String SHA1(String text) throws NoSuchAlgorithmException,
			UnsupportedEncodingException {
		MessageDigest md = MessageDigest.getInstance("SHA-1");
		md.update(text.getBytes("iso-8859-1"), 0, text.length());
		byte[] sha1hash = md.digest();
		return convertToHex(sha1hash);
	}

	public static String getFechaSistema() {
		String fechaActual = "";
		Date fecha = new Date();
		SimpleDateFormat formato = new SimpleDateFormat("yyyy-MM-dd H:mm");
		fechaActual = formato.format(fecha);
		return fechaActual;
	}

	public static String convertStreamToString(InputStream is) {
		/*
		 * To convert the InputStream to String we use the
		 * BufferedReader.readLine() method. We iterate until the BufferedReader
		 * return null which means there's no more data to read. Each line will
		 * appended to a StringBuilder and returned as String.
		 */
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	public static Boolean enviarNotificacionViaMail(String mailInfractor) {
		Boolean isMailed = false;
		String urlWs = "http://webservice.osirix.co/?";
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget;
		HttpResponse response;

		// lista de parametros, para agregarlos al string de la ruta del WS
		List<NameValuePair> params = new LinkedList<NameValuePair>();

		params.add(new BasicNameValuePair("a", "3"));
		// params.add(new BasicNameValuePair("u", user));
		// params.add(new BasicNameValuePair("c", pass));
		params.add(new BasicNameValuePair("m", mailInfractor));

		String stringParams = URLEncodedUtils.format(params, "utf-8");
		urlWs += stringParams;
		httpget = new HttpGet(urlWs);

		try {
			response = httpclient.execute(httpget);
			// se verifica la respuesta a la solicitud
			Log.i("OsirixCE", response.getStatusLine().toString());
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				InputStream instream = entity.getContent();
				String result = Util.convertStreamToString(instream);
				Log.i("OsirixCE", result);

				// A Simple JSONObject Creation
				JSONObject json = new JSONObject(result);
				Log.i("Praeda", "<jsonobject>\n" + json.toString()
						+ "\n</jsonobject>");

				// A Simple JSONObject Parsing
				JSONArray nameArray = json.names();
				JSONArray valArray = json.toJSONArray(nameArray);

				// se recorre el Objeto JsonArray que contiene los datos de
				// respuesta del WS
				for (int i = 0; i < valArray.length(); i++) {
					Log.i("Praeda",
							"<jsonname" + i + ">\n" + nameArray.getString(i)
									+ "\n</jsonname" + i + ">\n" + "<jsonvalue"
									+ i + ">\n" + valArray.getString(i)
									+ "\n</jsonvalue" + i + ">");

					// se valida si el json 'error' tiene como valor '0' para
					// validar al usuario
					if (nameArray.getString(i).equals("error")
							&& valArray.getString(i).equals("4")) {
						// mostrarNotificacionGeneracionComparendoyEnvioCorreoExitoso();
						isMailed = true;
					}
				}				
				instream.close();
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return isMailed;
	}
	
	
}
